<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CourseScore extends Model
{
    //
    protected $table = 'course_score';  

    protected $primaryKey = 'id';

    protected $fillable = ['id','c_id','u_id','cost','score','effect ','teachers','environment','content','to_comment_id', 'to_user_id'];
   	
   	public function user(){
   		return $this->hasOne('App\User','id','u_id');
   	}

    public function childComments()
    {
        return $this->hasMany('App\Models\CourseScore','to_comment_id','id');
    }

    /**
     * 获取该课程各种评价类型的平均分
     */
    public function avgscore($id,$field)
    {
        $query = DB::table($this->table)->where('c_id','=',$id);
        if($field == 'score')
        {
            $query->select(DB::raw('count(*) as count'),DB::raw('SUM(score) AS scores'));
        }
        if($field == 'effect')
        {
            $query->select(DB::raw('count(*) as count'),DB::raw('SUM(effect) AS effs'));
        }
        if($field == 'teachers')
        {
            $query->select(DB::raw('count(*) as count'),DB::raw('SUM(teachers) AS teas'));
        }
        if($field == 'environment')
        {
            $query->select(DB::raw('count(*) as count'),DB::raw('SUM(environment) AS envs'));
        }
        $result = $query->first();

        return $result;
    }

    /**
     * 获取该课程的总体评价各个星级的平均分
     */
    public function starscore($id,$score)
    {
        return DB::table('course_score')
            ->select(DB::raw('count(*) as count'))
            ->where('c_id','=',$id)
            ->where('score','=',$score)
            ->first();
    }

}
